Page({
  data: {
    currentTab: 'reservation', // 'reservation' 或 'queue'
    
    // 预约相关数据
    currentReservation: {
      people: '1-2人',
      date: '10月21日今日',
      time: '15:00-16:30'
    },
    
    // 日期选择
    dates: [
      { label: '今天 10-22', value: 'today', active: true },
      { label: '明天 10-23', value: 'tomorrow', active: false },
      { label: '后天 10-24', value: 'dayAfter', active: false },
      { label: '星期一 10-25', value: 'monday', value: false }
    ],
    
    // 就餐人数
    peopleCount: '6人',
    
    // 桌型选择
    tableTypes: [
      { name: '小桌 1-2人', capacity: '1-2', active: true },
      { name: '中桌 3-4人', capacity: '3-4', active: false },
      { name: '大桌 6-8人', capacity: '6-8', active: false }
    ],
    
    // 时间段选择
    timeSlots: [
      ['15:00', '16:30', '17:00'],
      ['15:00', '16:30', '17:00']
    ],
    
    // 选中的时间段
    selectedTimeSlot: '15:00',
    
    // 预约信息
    reservationInfo: {
      date: '',
      people: '',
      tableType: '',
      timeSlot: ''
    }
  },

  onLoad() {
    this.initDates()
  },

  // 初始化日期
  initDates() {
    const today = new Date()
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)
    const dayAfter = new Date(today.getTime() + 2 * 24 * 60 * 60 * 1000)
    const monday = new Date(today.getTime() + 3 * 24 * 60 * 60 * 1000)
    
    const dates = [
      { label: `今天 ${this.formatDate(today)}`, value: 'today', active: true },
      { label: `明天 ${this.formatDate(tomorrow)}`, value: 'tomorrow', active: false },
      { label: `后天 ${this.formatDate(dayAfter)}`, value: 'dayAfter', active: false },
      { label: `星期一 ${this.formatDate(monday)}`, value: 'monday', active: false }
    ]
    
    this.setData({ dates })
  },

  // 格式化日期
  formatDate(date) {
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${month}-${day}`
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      currentTab: tab
    })
  },

  // 选择日期
  selectDate(e) {
    const index = e.currentTarget.dataset.index
    const dates = this.data.dates.map((date, i) => ({
      ...date,
      active: i === index
    }))
    
    this.setData({ dates })
  },

  // 选择桌型
  selectTableType(e) {
    const index = e.currentTarget.dataset.index
    const tableTypes = this.data.tableTypes.map((type, i) => ({
      ...type,
      active: i === index
    }))
    
    this.setData({ tableTypes })
  },

  // 选择时间段
  selectTimeSlot(e) {
    const timeSlot = e.currentTarget.dataset.time
    this.setData({
      selectedTimeSlot: timeSlot
    })
  },

  // 调整就餐人数
  adjustPeopleCount() {
    wx.showActionSheet({
      itemList: ['1人', '2人', '3人', '4人', '5人', '6人', '7人', '8人'],
      success: (res) => {
        const peopleCount = `${res.tapIndex + 1}人`
        this.setData({ peopleCount })
      }
    })
  },

  // 立即预约
  reserveNow() {
    const { dates, peopleCount, tableTypes, selectedTimeSlot } = this.data
    
    // 获取选中的日期
    const selectedDate = dates.find(date => date.active)
    
    // 获取选中的桌型
    const selectedTableType = tableTypes.find(type => type.active)
    
    // 验证选择
    if (!selectedDate || !selectedTableType || !selectedTimeSlot) {
      wx.showToast({
        title: '请完善预约信息',
        icon: 'none'
      })
      return
    }

    // 检查是否已有预约
    this.checkExistingReservation()
  },

  // 检查是否已有预约
  checkExistingReservation() {
    // 模拟检查已有预约
    const hasExistingReservation = Math.random() > 0.5
    
    if (hasExistingReservation) {
      this.showExistingReservationDialog()
    } else {
      this.processReservation()
    }
  },

  // 显示已有预约提示
  showExistingReservationDialog() {
    wx.showModal({
      title: '提示',
      content: '您已预约过该商家的餐位，是否继续预约？',
      confirmText: '确定',
      cancelText: '查看我的预约',
      success: (res) => {
        if (res.confirm) {
          this.processReservation()
        } else {
          this.viewMyReservations()
        }
      }
    })
  },

  // 查看我的预约
  viewMyReservations() {
    wx.navigateTo({
      url: '/pages/profile/profile'
    })
  },

  // 处理预约
  processReservation() {
    const { dates, peopleCount, tableTypes, selectedTimeSlot } = this.data
    
    const selectedDate = dates.find(date => date.active)
    const selectedTableType = tableTypes.find(type => type.active)
    
    const reservationData = {
      date: selectedDate.label,
      people: peopleCount,
      tableType: selectedTableType.name,
      timeSlot: selectedTimeSlot
    }

    wx.showLoading({
      title: '预约中...'
    })

    // 模拟预约处理
    setTimeout(() => {
      wx.hideLoading()
      
      wx.showToast({
        title: '预约成功',
        icon: 'success'
      })

      // 保存预约信息
      this.saveReservation(reservationData)

      // 延迟返回
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }, 2000)
  },

  // 保存预约信息
  saveReservation(data) {
    try {
      const reservations = wx.getStorageSync('reservations') || []
      reservations.push({
        ...data,
        id: Date.now(),
        createTime: new Date().toISOString(),
        status: 'confirmed'
      })
      wx.setStorageSync('reservations', reservations)
    } catch (error) {
      console.error('保存预约信息失败:', error)
    }
  },

  // 返回首页
  backToHome() {
    wx.navigateTo({
      url: '/pages/index/index'
    })
  }
}) 